<template>
    <div>
        <el-dialog :title="title"
            v-model="dialogConfig.show" 
            width="400px"
            @close="closeDialog"
            >
            <el-form
            :model="formData"
            :rules="rules"
            ref="formDataRef"
            >
                <el-form-item prop="email">
                    <el-input size="large" maxlength="150" clearable placeholder="请输入邮箱" v-model="formData.email">
                        <template #prefix>
                            <span class="iconfont icon-account"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password" v-if="opType === 1">
                    <el-input maxlength="18" :type="passwordEyeType.passwordEyeOpen ?'text' : 'password'" size="large" clearable placeholder="请输入密码" v-model="formData.password">
                        <template #prefix>
                            <span class="iconfont icon-password"></span>
                        </template>
                        <template #suffix>
                           <span @click="eyeChange('passwordEyeOpen')" :class = "['iconfont',passwordEyeType.passwordEyeOpen?'icon-eye':'icon-close-eye']"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <!-- 注册 -->
                <div v-if="opType === 0 || opType === 2">
                    <el-form-item prop="emailCode">
                    <div class="send-email-panel">
                       <el-input size="large" clearable placeholder="请输入邮箱验证码" v-model="formData.emailCode">
                            <template #prefix>
                                <span class="iconfont icon-checkcode"></span>
                            </template>
                        </el-input> 
                        <el-button @click="getEmailCode" class="send-email-button" size="large" type="primary">获取验证码</el-button>
                    </div>
                    <div style="height: 20px;">
                        <el-popover placement="left" width="300px" trigger="click">
                            <div>
                                <p>1、在垃圾箱中查找验证码</p>
                                <p>2、重新发送</p>
                                <p>3、将邮箱【xxxx】添加到白名单</p>
                            </div>
                        <template #reference>
                            <span class="a-link" :style="{'font-size' : '12px',}">未收到验证码？</span>
                        </template>
                    </el-popover>
                    </div>
                    
                </el-form-item>
                <el-form-item prop="nickName" v-if="opType === 0 ">
                    <el-input size="large" maxlength="20" clearable placeholder="请输入昵称" v-model="formData.nickName">
                        <template #prefix>
                            <span class="iconfont icon-account"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="regPassword">
                    <el-input :type="passwordEyeType.regPasswordEyeOpen ?'text' : 'password'" size="large" clearable placeholder="请输入密码" v-model="formData.regPassword">
                        <template #prefix>
                            <span class="iconfont icon-password"></span>
                        </template>
                        <template #suffix>
                           <span @click="eyeChange('regPasswordEyeOpen')" :class = "['iconfont',passwordEyeType.regPasswordEyeOpen?'icon-eye':'icon-close-eye']"></span>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item prop="reRegPassword">
                    <el-input :type="passwordEyeType.reRegPasswordEyeOpen ?'text' : 'password'" size="large" clearable placeholder="请再次输入密码" v-model="formData.reRegPassword">
                        <template #prefix>
                            <span class="iconfont icon-password"></span>
                        </template>
                        <template #suffix>
                           <span @click="eyeChange('reRegPasswordEyeOpen')" :class = "['iconfont',passwordEyeType.reRegPasswordEyeOpen?'icon-eye':'icon-close-eye']"></span>
                        </template>
                    </el-input>
                </el-form-item>
                </div>
                
                <el-form-item prop="checkCode">
                    <div class="check-code-panel">
                       <el-input size="large" clearable placeholder="请输入验证码" v-model="formData.checkCode">
                            <template #prefix>
                                <span class="iconfont icon-checkcode"></span>
                            </template>
                        </el-input> 
                        <img :src="checkCodeUrl" class="check-code" @click="changeCheckCode(0)"/>
                    </div>
                </el-form-item>
                <el-form-item v-if="opType === 1">
                    <div class="remember-panel">
                        <el-checkbox v-model="formData.rememberMe">记住我</el-checkbox>
                    </div>
                    <div class="no-account-panel">
                        <a href="javascript:;" class="a-link" @click="showPanel(2)">忘记密码？</a>
                        <a href="javascript:;" class="a-link" @click="showPanel(0)">没有账号？</a>
                    </div>
                </el-form-item>
                <el-form-item v-if="opType === 0 ">
                    <div class="no-account-panel">
                        <a href="javascript:;" class="a-link" @click="showPanel(1)">已有账号？</a>
                    </div>
                </el-form-item>
                <el-form-item v-if="opType === 2 ">
                    <div class="no-account-panel">
                        <a href="javascript:;" class="a-link" @click="showPanel(1)">去登录</a>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="width: 100%;" @click="submitForm()" >
                        <span v-if="opType ==0">注册</span>
                        <span v-if="opType ==1">登录</span>
                        <span v-if="opType ==2">重置密码</span>
                    </el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 发送邮箱验证码 -->
        <el-dialog :title= sendEmailTitle
            v-model="emailDialogConfig.show" 
            width="400px"
            @close="emailDialogConfig.show = false"
            >
            <el-form :model="formData4SendEmailCode" :rules="rules" ref="formData4SendEmailCodeRef" >
                <el-form-item label="邮箱" >{{ formData.email }}</el-form-item>

                <el-form-item label="验证码" prop="checkCode">
                    <div class="check-code-panel">
                       <el-input size="large" clearable placeholder="请输入验证码" v-model="formData4SendEmailCode.checkCode">
                            <template #prefix>
                                <span class="iconfont icon-checkcode"></span>
                            </template>
                        </el-input> 
                        <img :src="checkCodeUrl4SendEmailCode" class="check-code" @click="changeCheckCode(1)"/>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button @click="sendEmailCode" style="margin-left: auto;" type="primary">发送验证码</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive,computed, getCurrentInstance, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { md5 } from 'js-md5';
import { useStore } from 'vuex';
const { proxy } = getCurrentInstance();
const store = useStore();
const router = useRouter();
const route = useRoute();

const sendEmailTitle = "发送验证码"

const api = {
    checkCode : "/api/checkCode",
    sendEmailCode : "/sendEmailCode",
    register:"/register",
    login:"/login",
    resetPwd:"/resetPwd",
}

const dialogConfig = reactive({
  show: false
});
const formData4SendEmailCode =ref({});
const formData4SendEmailCodeRef=ref({})

// 发送邮箱验证码
const getEmailCode=()=>{
    formDataRef.value.validateField("email",(valid)=>{
        if(!valid){
            return;
        }
        emailDialogConfig.show = true;

        nextTick(()=>{
            changeCheckCode(1);
            formData4SendEmailCodeRef.value.resetFields();
            formData4SendEmailCode.value = {email : formData.value.email };
        })

    })
}
const emailDialogConfig = reactive({
  show: false
});
// 发送邮件
const sendEmailCode = ()=>{
    formData4SendEmailCodeRef.value.validate(async(valid)=>{
        if(!valid){
            return;
        }
        const params = Object.assign({} , formData4SendEmailCode.value)

        params.type = opType.value == 0 ? 0 : 1;//注册或者找回密码
        // params.type = 0 ;//注册或者找回密码
        console.log(params.type,"type")
        let result = await proxy.Request({
            url:api.sendEmailCode,
            params : params,
            errorCallback:()=>{
                changeCheckCode(1)
            }
        })
        if(!result){
            return;
        }
        // console.log("请求后台发送邮件验证码")
        proxy.Message.success("验证码发送成功，请登录邮箱查看");
        emailDialogConfig.show = false;
    })
}

//验证码
const checkCodeUrl = ref(api.checkCode);
const checkCodeUrl4SendEmailCode = ref(api.checkCode);
const changeCheckCode = (type)=>{
    if(type === 0){
        checkCodeUrl.value = api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
    }else{
        checkCodeUrl4SendEmailCode.value = api.checkCode + "?type=" + type + "&time=" + new Date().getTime();
    }
}

// 0:注册。1：登录。2:找回密码
const opType = ref()
const showPanel = (type)=>{
    opType.value = type;
    resetForm();
    
}
const title = computed(() => {
  switch (opType.value) {
    case 0:
      return '注册';
    case 1:
      return '登录';
    case 2:
      return '重置密码';
    default:
      return '错误';
  }
});

const eyeChange = (type)=>{
    passwordEyeType[type] = !passwordEyeType[type];
}

const passwordEyeType = reactive({
    passwordEyeOpen: false,
    regPasswordEyeOpen: false,
    reRegPasswordEyeOpen: false
})
//重置表单
const resetForm = ()=>{
    dialogConfig.show = true;
    changeCheckCode(0)
    
    nextTick(()=>{
        formDataRef.value.resetFields();
        formData.value = {};

        //登录
        if(opType.value == 1){
            const cookieLoginInfo = proxy.VueCookies.get("loginInfo");
            if(cookieLoginInfo){
                formData.value = cookieLoginInfo;
            }
        }
    })


}
defineExpose({showPanel})

const checkRePassword = (rule,value,callback)=>{
    if(value != formData.value.regPassword){
        callback(new Error(rule.message))
    }else{
        callback()
    }
}

const formData = ref({});
const formDataRef = ref({})

const rules = {
    email:[
        {required : true, message: '请输入邮箱', trigger: 'blur'},
        {validator:proxy.Verify.email,message: '请输入正确的邮箱', trigger: 'blur'}
    ],
    emailCode:[
        {required : true, message: '请输入邮箱验证码', trigger: 'blur'}
    ],
    password:[
        {required : true, message: '请输入密码', trigger: 'blur'}
    ],
    nickName:[{
        required : true, message: '请输入用户名', trigger: 'blur'
    }],
    regPassword:[
        {required : true, message: '请输入密码', trigger: 'blur'},
        {validator:proxy.Verify.password,message: '密码长度在8-18个字符之', trigger: 'blur'}
    ],
    reRegPassword:[
        {required : true, message: '请再次输入密码', trigger: 'blur'},
        {validator: checkRePassword,message:'密码不一致' , trigger: 'blur'}
    ],
    checkCode : [{required : true, message: '请输入验证码', trigger: 'blur'}]
}

// 提交表单
const submitForm = ()=>{
    formDataRef.value.validate(async(valid)=>{
        if(!valid){
            return;
        }
        let params ={};
        Object.assign(params,formData.value);

        //注册
        if(opType.value === 0 || opType.value === 2){
            params.password = params.regPassword;
            delete params.regPassword;
            delete params.reRegPassword;
        }

        //登录
        if(opType.value === 1){
            let cookieLoginInfo = proxy.VueCookies.get("loginInfo");
            let cookPassword = cookieLoginInfo==null?null:cookieLoginInfo.password;
            if(params.password != cookPassword){
                params.password = md5(params.password);
            }
        }

        let url= null;
        if(opType.value == 0){
            url = api.register;
        }else if(opType.value == 1){
            url = api.login;
        }else if(opType.value == 2){
            url = api.resetPwd;
        }

        let result = await proxy.Request({
            url:url,
            params : params,
            errorCallback:()=>{
                changeCheckCode(0)
            }
        })
        if(!result){
            return;
        }
        //注册返回
        if(opType.value === 0){
            proxy.Message.success("注册成功，请登录");
            showPanel(1);
        }else if(opType.value === 1){
            //登录
            if(params.rememberMe){
                const loginInfo = {
                    email : params.email,
                    password : params.password,
                    rememberMe : params.rememberMe,
                };
                proxy.VueCookies.set("loginInfo",loginInfo,"7d");
            }else{
                proxy.VueCookies.remove("loginInfo");
            }
            dialogConfig.show = false;;
            proxy.Message.success("登录成功");  
            store.commit('updateLoginUserInfo',result.data)
        }else if(opType.value === 2){
            //重置密码
            proxy.Message.success("重置密码成功，请登录");
            showPanel(1);
        }
    })
}

const closeDialog = ()=>{
    dialogConfig.show = false;
    store.commit('showLogin',false)
}

</script>

<style lang="scss">
.send-email-panel{
    display: flex;
    align-items: center;

    .send-email-button {
        margin-left: 10px; // 调整间距
    }
}

.check-code-panel{
    display: flex;
    align-items: center;

    .check-code {
        margin-left: 10px; // 调整间距
    }
}

.remember-panel {
    width: 100%;;
    margin-bottom: 10px; // 调整间距
}

.no-account-panel {
    width: 100%;
    display: flex;
    justify-content: space-between;
}
</style>